package org.helgoboss.build_helgoboss_commons

import org.gradle.api._
import groovy.lang.Closure
import _root_.java.io._
import scala.xml.PrettyPrinter
import org.helgoboss.scala_additions.Implicits._
import org.helgoboss.scala_additions.currentRuntime

class BuildHelgobossCommons extends Plugin[Project] {
    def apply(project: Project) {        
        val task = new Closure(this) {
            val versions = System.getProperty("versions")
            val root = {
                val tmp = System.getProperty("root")
                if (tmp == null) {
                    new File(".")
                } else {
                    new File(tmp)
                }
            }
            override def call: AnyRef = {
                val projects = versions match {
                    case "trunks" => 
                        root.tree.include("*/trunk").exclude("helgoboss-obr-builder/**", "autoproxy-plugin/**", "clean-local-obr-repository/**", "user-notification/**").filter(_.file.tree.exists(_.path matches "pom.xml")).map(_.path)
                    
                    case "tags" => 
                        root.tree.include("*/tags").flatMap { node =>
                            node.file.tree(walkOrder = Some(_.getName > _.getName)).
                                    exclude(".svn", "*/**", "").map(node.path / _.path).take(1)
                        }
                }

                val pom = <project xmlns="http://maven.apache.org/POM/4.0.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
                    <modelVersion>4.0.0</modelVersion>
                    
                    <parent>
                        <groupId>org.helgoboss</groupId>
                        <artifactId>helgoboss-parent</artifactId>
                        <version>0.4</version>
                    </parent>
                    <artifactId>helgoboss-commons-parent</artifactId>
                    <version>0.1-SNAPSHOT</version>
                    <name>Just an aggregator for all the helgoboss-commons projects. Is not supposed to be a parent project.</name>
                    <packaging>pom</packaging>
                    <modules>
                        {
                            projects.map { path =>
                                <module>{path.components.mkString("/")}</module>
                            }
                        }
                    </modules>
                </project>

                new File("pom.xml").content = new PrettyPrinter(80, 4).format(pom)
                currentRuntime.execute("mvn.bat", "clean", "install").output.text.getLines.foreach(println)
                
                null
            }
        }
        project.task("build-helgoboss-commons", task)
    }
}